package com.tanhua.dubbo.Api;

import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.model.mongo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

/**
 * @author 刘付磊
 * @date 2021/11/21 0021
 */
@DubboService
public class UserLikeApiImpl implements UserLikeApi {

    @Autowired
    private MongoTemplate template;

    @Override
    public Boolean saveOrupdate(Long likeUserId, Long userId, boolean isLike) {
        try {
            //1.查询数据
            Query query = Query.query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));
            UserLike userLike = template.findOne(query, UserLike.class);
            //2.如果不存在 保存
            if (userLike == null) {
                UserLike user = new UserLike();
                user.setIsLike(isLike);
                user.setUserId(userId);
                user.setLikeUserId(likeUserId);
                user.setCreated(System.currentTimeMillis());
                user.setUpdated(System.currentTimeMillis());
                template.save(user);
            } else {
                Update update = Update.update("isLike", isLike).set("updated", System.currentTimeMillis());
                template.updateFirst(query, update, UserLike.class);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
